/*
 * 自写常用方法
 * */
import moment from 'moment';
import {stringify} from 'qs';
import MD5 from 'md5.js';


const G = {

    uuid(len, radix) {
        var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var chars = CHARS, uuid = [], i;
        radix = radix || chars.length;
        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    },

    getUrlValue(name, url)//获取URL参数
    {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        url = url || window.location.hash; //默认取当前URL匹配
        var matchUrl = '?' + url.split('?')[1];

        if (matchUrl.substr(1).match(reg)) {
            var arr = matchUrl.substr(1).match(reg);
            return decodeURIComponent(arr[2]);
        } else {
            return undefined;
        }
    },

    setCookie(name, value){//写cookies
        var Days = 1000;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;domain=.gearkr.com";
        //  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;";
    },

    getCookie(name)
    {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    },

    delCookie(name)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = this.getCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    },

    formAtTime(time = new Date()){
        return moment(time).format('YYYY-MM-DD HH:mm:ss');
    },

    preloadImg(url, callback){
        var img = new Image(); //创建一个Image对象，实现图片的预下载
        img.src = url;

        if (img.complete) { // 如果图片已经存在于浏览器缓存，直接调用回调函数
            callback.call(img, img.width, img.height);
            return; // 直接返回，不用再处理onload事件
        }

        img.onload = function () { //图片下载完毕时异步调用callback函数。
            callback.call(img, img.width, img.height);//将回调函数的this替换为Image对象
        };
    },
    md5Encrypt(obj = {}){
        const sortKey = Object.keys(obj).sort();  //对加密参数先ASCII码排序，后加密
        let signStr = '';
        sortKey.forEach(v=> {
            if (obj[v]) {
                signStr += `${v}=${obj[v]}&`
            }
        });
        console.log(signStr);
        const sign = (new MD5().update(`${signStr}key=T47RrHW68tuqLpvVs5Scj3ChoEYUX9Id`).digest('hex')).toUpperCase();
        return sign;
    },
    openH5(url){
        var left = (document.body.clientWidth - 400 )/ 2;
        window.open(url, 'newwindow', 'height=700, width=400, top=0, left=' + left + ', toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');   //该句写成一行代码
    },
    openPc(url){
      var left = (document.body.clientWidth - 1000 )/ 2;
      window.open(url, 'newwindow', 'height=900, width=1000, top=0, left=' + left + ', toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');   //该句写成一行代码
    }
}

// if (G.getCookie('X-APIHitgou-ClientId') == null) {
//     G.setCookie('X-APIHitgou-ClientId', '02' + G.uuid(32));
// }
if (typeof window.localStorage.clientId == 'undefined') {
  window.localStorage.clientId = '02' + G.uuid(32)
}

export default G;
